package jinyilw.swing.visuals.Jcomp;

import jinyilw.common.Operator;
import jinyilw.swing.ComponentTools;
import jinyilw.swing.icon.LazyScaleIcon;
import jinyilw.swing.image.ImageTools;

import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class JActImageComp extends JMouseActComp
{
	private static final long serialVersionUID = -1276675463020135887L;
	private LazyScaleIcon scaleIcon;
	protected Image image, overImage;

	public JActImageComp()
	{
		enableMouseAct();
	}

	public JActImageComp(Image img)
	{
		this();
		setImage(img);
	}

	public JActImageComp(Image image, Image overImage)
	{
		this();
		this.image = image;
		this.overImage = overImage;
	}

	public JActImageComp(LazyScaleIcon icon)
	{
		this(icon.getImage(), icon.getOverImage());
		scaleIcon = icon;
		setSize(icon.getIconWidth(), icon.getIconHeight());
	}

	public void setImage(Image img)
	{
		if (image != img)
		{
			image = img;
			if (img != null)
				overImage = ImageTools.getContrastLightImage(img, 1.5f, 1.5f);
			if (isShowing())
				repaint();
		}
	}

	public void setImage(Image image, Image overImage)
	{
		this.image = image;
		this.overImage = overImage;
		if (isShowing())
			repaint();
	}

	public Image getImage()
	{
		return image;
	}

	public void addDoubleClickOperator(final Operator<MouseEvent> operator)
	{
		this.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (isEnabled() && e.getClickCount() == 2)
					operator.operate(e);
			}
		});
	}

	@Override
	public Dimension getPreferredSize()
	{
		if (scaleIcon == null)
			return super.getPreferredSize();
		return new Dimension(scaleIcon.getSize());
	}

	@Override
	protected void paintComponent(Graphics g)
	{
		Image img = isRollover ? overImage : image;
		if (img != null)
		{
			Insets insets = getInsets();
			int width = getWidth() - insets.left - insets.right;
			int height = getHeight() - insets.top - insets.bottom;
			boolean isEnabled = isEnabled();
			Graphics2D g2d = (Graphics2D) g;
			Composite composite = ComponentTools.applyEnableAlpha(g2d,
					isEnabled, 1f, 0.3f);
			if (isEnabled && isPressed)
				g2d.translate(0.9, 0.9);
			g2d.drawImage(img, insets.left, insets.top, width, height, null);
			if (isEnabled && isPressed)
				g2d.translate(-0.9, -0.9);
			if (composite != null)
				g2d.setComposite(composite);
		}
	}

	public void clearImage()
	{
		image = null;
		overImage = null;
		if (isShowing())
			repaint();
	}
}
